package com.example.client.controller.user;

import com.example.commonapi.pojo.User;
import com.example.userservice.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    private static final Log logger = LogFactory.getLog(UserController.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Reference(version = "${demo.service.version}")
    UserService userService;

    /**
     * 登录
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        session.removeAttribute("user");
        logger.info("\nid为" + user.getId() + "的用户退出了登录");
        return "forward:/";
    }

    /**
     * 注册
     * @return
     */
    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    /**
     * 用户信息
     * @param id
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/user/info/{id}")
    public String userInfo(@PathVariable("id") String id, HttpServletRequest request) throws JsonProcessingException {
        User user = userService.getUserById(Integer.parseInt(id));
        request.setAttribute("user", user);

        return "user/user-info";
    }

    /**
     * 更改密码
     * @param request
     * @return
     */
    @RequestMapping("/user/update")
    public String userUpdate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        request.setAttribute("user", user);
        return "user/user-update-password";
    }


}
